<?php

declare(strict_types=1);


namespace App\CustHub\Controller;

use App\Common\Constants\ErrorCode;
use App\Common\Helpers\SortHelper;
use App\CustHub\Annotation\ApiAuth;
use App\CustHub\Annotation\ChPermission;
use App\CustHub\Annotation\VerifySignature;
use App\CustHub\Constants\RobotApplyConstants;
use App\CustHub\Constants\SendConfigConstants;
use App\CustHub\Model\ChCrowdSending;
use App\CustHub\Model\ChCrowdSendingGroup;
use App\CustHub\Model\ChSmartAnswer;
use App\CustHub\Model\ChSmartQuestionnaire;
use App\CustHub\Model\ChSmartQuestionnaireAnswer;
use App\CustHub\Model\ChSmartQuestionnaireItem;
use App\CustHub\Model\ChSop;
use App\CustHub\Model\ChSopTemplate;
use App\CustHub\Model\ChWord;
use App\CustHub\Model\ChWordGroup;
use App\CustHub\Service\ChRobotApplyService;
use App\CustHub\Service\ChSendConfigService;
use App\CustHub\Service\ChSopService;
use App\CustHub\Service\QuestionnaireService;
use App\Enum\WordTypeEnum;
use App\Exception\BusinessException;
use Hyperf\DbConnection\Db;
use Hyperf\HttpServer\Annotation\Controller;
use Hyperf\HttpServer\Annotation\PostMapping;
use App\CustHub\Service\ChUserService;
use Hyperf\Di\Annotation\Inject;

#[Controller(prefix: 'ch/questionnaire'),ApiAuth,VerifySignature]
class QuestionnaireController extends BaseController
{
    #[Inject]
    protected QuestionnaireService $service;

    public array $noNeedLogin = [''];

    /**
     * 添加模板
     * @return \Psr\Http\Message\ResponseInterface
     * @throws \Psr\Container\ContainerExceptionInterface
     * @throws \Psr\Container\NotFoundExceptionInterface
     */
    #[PostMapping('add'),ChPermission('ch:questionnaire:add')]
    public function addQuestionnaire()
    {
        $this -> validateParam([
            'content' => 'required',
            'corp_id' => 'required',
        ]);
        $uid =$this->request->input('uid');
        $mainUid = $this->request->input('main_uid');
        $corpId = $this->request->input('corp_id');
        $params = $this -> request -> all();
        $content = is_array($params['content'])?$params['content']:json_decode($params['content'],true);
        $res = $this -> service -> saveQuestionnaire($uid,$mainUid,$corpId,$content);
        return $this -> success('添加成功',$res);
    }


    #[PostMapping('edit'),ChPermission('ch:questionnaire:edit')]
    public function editQuestionnaire()
    {
        $this -> validateParam([
            'content' => 'required',
            'corp_id' => 'required',
            'id' => 'required',
        ]);
        $uid =$this->request->input('uid');
        $id =$this->request->input('id');
        $mainUid = $this->request->input('main_uid');
        $corpId = $this->request->input('corp_id');
        $params = $this -> request -> all();
        $content = is_array($params['content'])?$params['content']:json_decode($params['content'],true);
        $res = $this -> service -> saveQuestionnaire($uid,$mainUid,$corpId,$content,$id);
        return $this -> success('修改成功',$res);
    }

    #[PostMapping('detail'),ChPermission('ch:questionnaire:detail')]
    public function detail()
    {
        $this -> validateParam([
            'id' => 'required',
        ]);
        $uid =$this->request->input('uid');
        $mainUid = $this->request->input('main_uid');
        $id = $this->request->input('id');
        $res = $this -> service -> getDetail($id);
        return $this -> success('获取成功',$res);
    }

    #[PostMapping('list'),ChPermission('ch:questionnaire:list')]
    public function List()
    {
        $uid =$this->request->input('uid');
        $mainUid = $this->request->input('main_uid');
        $page_size =$this->request->input('page_size',15);
        $params = $this -> request -> all();

        $where = [];
        if (!empty($params['keyword'])) {
             $where[] = ['title', 'like', "%" . $params['keyword'] . "%"];
        }
        if (not_empty($params['status'])) {
            $where[] = ['status', $params['status']];
        }
        if (!empty($params['corp_id'])) {
            $where[] = ['corp_id', $params['corp_id']];
        }
        $page = ChSmartQuestionnaire::query() -> with(['user' => function ($q) {
            $q->select('id', 'nickname');
        }]) -> where($where) -> select(['title','id','created_at','updated_at','corp_id','status','forever','end_at','uid','main_uid','click_total','submit_total','write_total']) -> paginate((int)$page_size);
        $list = $page -> items();
        $total = $page -> total();
        return $this -> success('获取成功',['list'=>$list,'total'=>$total]);
    }

    #[PostMapping('delete'),ChPermission('ch:questionnaire:delete')]
    public function delete()
    {
        $this -> validateParam([
            'id' => 'required',
        ]);
        $id =$this->request->input('id');
        if(ChSmartQuestionnaireAnswer::query() -> where('questionnaire_id',$id) -> count() > 0){
            return $this -> error('已经有用户回答不可删除',ErrorCode::CANNOT_DELETE);
        }
        ChSmartQuestionnaire::query() -> where('id',$id) -> delete();
        ChSmartQuestionnaireItem::query() -> where('questionnaire_id',$id) -> delete();
        return $this -> success('删除成功');
    }

    #[PostMapping('publish'),ChPermission('ch:questionnaire:publish')]
    public function publish()
    {
        $this -> validateParam([
            'id' => 'required',
            'forever' => 'required'
        ]);
        $id =$this->request->input('id');
        $forever =$this->request->input('forever');
        $end_at =$this->request->input('end_at');
        $questionnaire = ChSmartQuestionnaire::query() -> where('id',$id) -> first();
        if(empty($questionnaire)) throw new BusinessException(ErrorCode::NOT_ISSET,'数据不存在');
        if($questionnaire -> status != 0) throw new BusinessException(ErrorCode::SERVICE_DELETE,'状态不可发布');
        ChSmartQuestionnaire::query() -> where('id',$id) -> update([
            'forever' => $forever,
            'end_at' => $end_at,
            'status' => 1
        ]);
        return $this -> success('发布成功');
    }

    #[PostMapping('deadline'),ChPermission('ch:questionnaire:deadline')]
    public function deadline()
    {
        $this -> validateParam([
            'id' => 'required',
            'forever' => 'required'
        ]);
        $id =$this->request->input('id');
        $questionnaire = ChSmartQuestionnaire::query() -> where('id',$id) -> first();
        if(empty($questionnaire)) throw new BusinessException(ErrorCode::NOT_ISSET,'数据不存在');
        if($questionnaire -> status != 1) throw new BusinessException(ErrorCode::SERVICE_DELETE,'状态不可操作');
        ChSmartQuestionnaire::query() -> where('id',$id) -> update([
            'status' => 2
        ]);
        return $this -> success('截止成功');
    }

    #[PostMapping('answer'),ChPermission('ch:questionnaire:answer')]
    public function answer()
    {
        $this -> validateParam([
            'questionnaire_id' => 'required',
            'avatar' => 'required',
            'nickname' => 'required',
            'openid' => 'required',
            'answer_content' => 'required',
        ]);
        $data = $this->request->input('answer_content');
        $questionnaire_id = $this->request->input('questionnaire_id');
        $openid = $this->request->input('openid');
        if(ChSmartQuestionnaireAnswer::query() -> where('questionnaire_id',$questionnaire_id) -> where('open_id',$openid) -> count() > 0){
            return $this -> error('已经提交过了',ErrorCode::ALREADY_SUBMIT);
        }
        $this -> service -> answer($questionnaire_id,$openid,'R','ttt.png',1,[]);
        return $this -> success('提交成功');
    }


    #[PostMapping('answer/detail'),ChPermission('ch:questionnaire:answer:detail')]
    public function answerDetail()
    {
        $this -> validateParam([
            'questionnaire_id' => 'required',
            'openid' => 'required',
        ]);
        $openid = $this->request->input('openid');
        $questionnaire_id = $this->request->input('questionnaire_id');
        $res = $this -> service -> getDetailWithAnswer($questionnaire_id,$openid);
        return $this -> success('获取成功',$res);
    }

    #[PostMapping('answer/analyse'),ChPermission('ch:questionnaire:answer:analyse')]
    public function itemAnalyse()
    {
        $this -> validateParam([
            'questionnaire_id' => 'required',
        ]);
        $openid = $this->request->input('openid');
        $questionnaire_id = $this->request->input('questionnaire_id');
        $res = $this -> service -> itemAnalyse($questionnaire_id);
        return $this -> success('获取成功',$res);
    }

    #[PostMapping('answer/user_list'),ChPermission('ch:questionnaire:answer:user_list')]
    public function user_list()
    {
        $this -> validateParam([
            'questionnaire_id' => 'required',
        ]);
        $openid = $this->request->input('openid');
        $questionnaire_id = $this->request->input('questionnaire_id');
        $res = $this -> service -> userList($questionnaire_id);
        return $this -> success('获取成功',$res);
    }


    #[PostMapping('answer/up_statistic'),ChPermission('ch:questionnaire:answer:up_statistic')]
    public function upStatistic()
    {
        $this -> validateParam([
            'questionnaire_id' => 'required',
            'source' => 'required',
            's_type' => 'required',
            'openid' => 'required',
        ]);
        $questionnaire_id = $this->request->input('questionnaire_id');
        $source = $this->request->input('source');
        $open_id = $this->request->input('openid');
        $s_type = $this->request->input('s_type');
        $res = $this -> service -> upStatistic($questionnaire_id,$source,$open_id,$s_type);
        return $this -> success('操作成功');
    }


    #[PostMapping('answer/statistic_source'),ChPermission('ch:questionnaire:answer:statistic_source')]
    public function statisticSource()
    {
        $this -> validateParam([
            'questionnaire_id' => 'required',
        ]);
        $questionnaire_id = $this->request->input('questionnaire_id');
        $res = $this -> service -> statistic($questionnaire_id);
        return $this -> success('获取成功',$res['source_static']);
    }

    #[PostMapping('answer/statistic'),ChPermission('ch:questionnaire:answer:statistic')]
    public function statistic()
    {
        $this -> validateParam([
            'questionnaire_id' => 'required',
        ]);
        $questionnaire_id = $this->request->input('questionnaire_id');
        $res = $this -> service -> statistic($questionnaire_id);
        return $this -> success('获取成功',$res['total_static']);
    }


}